package com.insectstudio.haiivloffical;

import java.util.ArrayList;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import android.app.ProgressDialog;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.webkit.JavascriptInterface;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.AbsListView;
import android.widget.ImageButton;
import android.widget.AbsListView.OnScrollListener;
import android.widget.TextView;

import com.androidquery.AQuery;
import com.androidquery.callback.AjaxCallback;
import com.androidquery.callback.AjaxStatus;
import com.google.android.gms.ads.AdRequest;
import com.google.android.gms.ads.AdView;
import com.google.android.gms.internal.pa;
import com.insectstudio.haiivloffical.adapter.haiivlAdapter;
import com.insectstudio.haiivloffical.customview.RefreshListView;
import com.insectstudio.haiivloffical.customview.RefreshListView.OnRefreshListener;
import com.insectstudio.haiivloffical.model.HaiivlItem;
import com.insectstudio.haiivloffical.utilities.NetworkUtility;

public class MainActivity extends MyActivity implements OnClickListener {

	private RefreshListView lvItem;
	private TextView txtTitle;
	private ImageButton btnList;

	int page = 0;
	String url = "";
	boolean isDownloading = false;
	private int preLast;
	ArrayList<HaiivlItem> arrItems = null;

	public ProgressDialog myProgressDialog ;
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		// get references
		lvItem = (RefreshListView) findViewById(R.id.lvItems);
		txtTitle = (TextView) findViewById(R.id.txt_title);
		btnList = (ImageButton) findViewById(R.id.btn_list);
		//
		mAdView = (AdView) findViewById(R.id.adView);
        AdRequest adRequest = new AdRequest.Builder().build();
        mAdView.loadAd(adRequest);
		// set title
		txtTitle.setText(getString(R.string.NewImage));
		btnList.setVisibility(View.VISIBLE);
		btnList.setOnClickListener(this);
		// get extra
		page = 1;
		url = Constants.NEW_METHOD;
		// get data
		arrItems = new ArrayList<HaiivlItem>();
		if (NetworkUtility.hasConnection(MainActivity.this)) {
			getHaiivlData(page);
		} else {
			showAlertDialog(getString(R.string.Alert), getString(R.string.NoInternetConnection));
		}
		// set on scroll listener
		lvItem.setOnScrollListener(new OnScrollListener() {

			@Override
			public void onScroll(AbsListView view, int firstVisibleItem,
					int visibleItemCount, int totalItemCount) {
				// TODO Auto-generated method stub
				switch (view.getId()) {
				case R.id.lvItems: {
					// Make your calculation stuff here. You have all your
					// needed info from the parameters of this function.

					// Sample calculation to determine if the last
					// item is fully visible.
					final int lastItem = firstVisibleItem + visibleItemCount;
					if (lastItem == totalItemCount) {
						if (preLast != lastItem) { // to avoid multiple calls for last item
							Log.d("Last", "Last");
							preLast = lastItem;
							if (isDownloading == false) {
								page++;
								getHaiivlData(page);
								if (page == 3 || (page > 3 && (page - 3) % 2 == 0)) {
									displayInterstitial();
								}
							}

						}
					}
					break;
				}

				}
			}

			@Override
			public void onScrollStateChanged(AbsListView arg0, int arg1) {
				// TODO Auto-generated method stub

			}
		});
		lvItem.setRefreshListener(new OnRefreshListener() {
			
			@Override
			public void onRefresh(RefreshListView listView) {
				// TODO Auto-generated method stub
//				if (NetworkUtility.hasConnection(MainActivity.this)) {
					page = 1;
					isDownloading = true;
					String url1 = url.replace("[page]", String.valueOf(page));
					AQuery aq = new AQuery(MainActivity.this);
					aq.ajax(url1, JSONObject.class, new AjaxCallback<JSONObject>() {
						@Override
						public void callback(String url, JSONObject json, AjaxStatus status) {
							try {
								if (page - 1 == 0)
									arrItems.clear();
								isDownloading = false;
								JSONArray dataArray = json.getJSONArray("data");
								
								if (dataArray == null || dataArray.length() == 0)
								{
									// server error
									// try to parse directly
									String newUrl = getDirectUrl(url,page); 
									parseDirectFromHaiiVl(newUrl);
								}else
								{
									for (int i = 0; i < dataArray.length(); i++) {
										JSONObject anItem = (JSONObject) dataArray.get(i);
										String title = anItem.getString("title");
										String imageUrl = anItem.getString("src");
										String video = anItem.getString("video_id");
										String gif = anItem.getString("src");
										String fullName = anItem.getString("full_name");
										int photoId = anItem.getInt("photo_id");
										int views = anItem.getInt("views");
										int comment = anItem.getInt("comment");
										int liked = anItem.getInt("liked");
		
										HaiivlItem item = new HaiivlItem(title, imageUrl,
												video, gif, fullName, photoId, views,
												comment, liked);
										arrItems.add(item);

									}
		
									haiivlAdapter adapter = new haiivlAdapter(
											MainActivity.this, R.layout.list_item_aspect_ratio,
											arrItems, new AQuery(MainActivity.this));
									lvItem.setAdapter(adapter);
		
									adapter.notifyDataSetChanged();
									// Setting new scroll position
									lvItem.setSelectionFromTop(0, 0);
									lvItem.finishRefreshing();
								}
								
							} catch (JSONException e) {
								// TODO Auto-generated catch block
								e.printStackTrace();
							}
						}
					});
//				} else {
//					lvItem.finishRefreshing();
//				}
				
			}
		});

	}

	void getHaiivlData(final int pageNum) {
		isDownloading = true;
		String url1 = url.replace("[page]", String.valueOf(pageNum));
		AQuery aq = new AQuery(MainActivity.this);
		aq.ajax(url1, JSONObject.class, new AjaxCallback<JSONObject>() {
			@Override
			public void callback(String url, JSONObject json, AjaxStatus status) {
				try {
					if (pageNum == 0)
						arrItems.clear();
					isDownloading = false;
					JSONArray dataArray = json.getJSONArray("data");
//					if (dataArray != null) {
					if (dataArray == null || dataArray.length() == 0)
					{
						// server error
						// try to parse directly
						String newUrl = getDirectUrl(url,pageNum); 
						parseDirectFromHaiiVl(newUrl);
					}else
					{
						for (int i = 0; i < dataArray.length(); i++) {
							JSONObject anItem = (JSONObject) dataArray.get(i);
							String title = anItem.getString("title");
							String imageUrl = anItem.getString("src");
							String video = anItem.getString("video_id");
							String gif = anItem.getString("src");
							String fullName = anItem.getString("full_name");
							int photoId = anItem.getInt("photo_id");
							int views = anItem.getInt("views");
							int comment = anItem.getInt("comment");
							int liked = anItem.getInt("liked");
	
							HaiivlItem item = new HaiivlItem(title, imageUrl,
									video, gif, fullName, photoId, views,
									comment, liked);
							arrItems.add(item);
	
						}
	
						haiivlAdapter adapter = new haiivlAdapter(
								MainActivity.this, R.layout.list_item_aspect_ratio,
								arrItems, new AQuery(MainActivity.this));
						lvItem.setAdapter(adapter);
	
						adapter.notifyDataSetChanged();
						// Setting new scroll position
						lvItem.setSelectionFromTop(preLast, 0);
					}
						
//					} else {
//						showAlertDialog(getString(R.string.Alert), getString(R.string.ServerMainternance));
//					}
				} catch (JSONException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		});
	}
	
	@Override
	protected void onPause() {
		// TODO Auto-generated method stub
        if (mAdView != null) {
            mAdView.pause();
        }
		super.onPause();
	}
	
	@Override
	protected void onResume() {
		// TODO Auto-generated method stub
		super.onResume();
        if (mAdView != null) {
            mAdView.resume();
        }
	}
	
	@Override
	protected void onDestroy() {
		// TODO Auto-generated method stub
        if (mAdView != null) {
            mAdView.destroy();
        }
		super.onDestroy();
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.main, menu);
		return true;
	}

	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
		switch (v.getId()) {
		case R.id.btn_list:
			toggle();
			break;
		}
		
	}

	//------------------//
	// Handle in case of can not get data from server
	public void parseDirectFromHaiiVl(String url)
	{
		myProgressDialog = ProgressDialog.show(MainActivity.this, "", "Đang tải dữ liệu", true); 
		 class MyJavaScriptInterface 
	        {
	        	@JavascriptInterface
	            public void showHTML(String html)
	            {
	        		Document doc;
	        		Document docDetail;
	        		try {
	        			doc = Jsoup.parse(html);
	        			Element element = doc.getElementsByClass("list-item").first();
	        			Element elementsListItem = element.getElementsByTag("div").first();
	        			
	        			Elements listCard = elementsListItem.children();
	        			for ( int i=0 ; i<listCard.size() ; i++ )
	        			{
	        				Element aListCard = listCard.get(i);
	        				String url = aListCard.getElementsByTag("a").first().attr("href") ; 
	        				String[] phoTosplits = url.split("/");
      					  	int photoId = 0 ;
      					  	if (phoTosplits.length > 1)
      					  	{
      					  		photoId = Integer.parseInt(phoTosplits[2]);
      					  	}
	        				String title = aListCard.getElementsByTag("a").first().html();
	        				String p = aListCard.getElementsByTag("p").first().html();
	        				Element itemBody = aListCard.getElementsByClass("item-body").first();
	        				String imageSource = "" ;
	        				String videoId = "";
	        				if (url.contains("video") == false)
	        				{
	        					imageSource = itemBody.getElementsByTag("img").first().attr("src");
	        					imageSource = "http:"+imageSource;
	        				}
	        				else
	        				{
	        					Pattern pattern = Pattern.compile("'([^']*)'");
	        					Matcher m = pattern.matcher(itemBody.html());
	        					while (m.find()) {
	        					  imageSource = m.group(1);
	        					  imageSource = "http:"+imageSource;
	        					  String[] splits = imageSource.split("/");
	        					  videoId = splits[4];
	        					  break;
	        					}
	        				}
	        				
	        				
	        				//Elements infos = aListCard.getElementsByTag("tabs-secondary") ; 
	        				String likes = aListCard.getElementsByTag("a").get(2).ownText() ; 
	        				String commend = aListCard.getElementsByTag("a").get(4).ownText() ; 
	        				
	        				HaiivlItem item = new HaiivlItem(title, imageSource,
	        						videoId, "", p,photoId, 0,
								Integer.parseInt(commend), Integer.parseInt(likes));
							arrItems.add(item);
							
							Log.e("list-item ", url + "  title " + title + " body " + imageSource );
	        			}
	        			
	        			runOnUiThread(new Runnable() {
	                        @Override
	                        public void run() {
	                        	
	                        	myProgressDialog.dismiss();
	                        	haiivlAdapter adapter = new haiivlAdapter(
	    								MainActivity.this, R.layout.list_item_aspect_ratio,
	    								arrItems, new AQuery(MainActivity.this));
	    						lvItem.setAdapter(adapter);
	    	
	    						adapter.notifyDataSetChanged();
	    						// Setting new scroll position
	    						lvItem.setSelectionFromTop(preLast, 0);
	                        }
	                    });
	        			

	        			
	        		}
	        		catch(Exception e)
	        		{
	        			e.printStackTrace();
	        		}
	                //Log.e("html", html);
	            }
	        }
	        
	        final WebView browser = new WebView(MainActivity.this);
	        browser.getSettings().setJavaScriptEnabled(true);
	        browser.getSettings().setLoadsImagesAutomatically(false);
	        /* Register a new JavaScript interface called HTMLOUT */
	        browser.addJavascriptInterface(new MyJavaScriptInterface(), "HTMLOUT");

	        /* WebViewClient must be set BEFORE calling loadUrl! */
	        browser.setWebViewClient(new WebViewClient() {
	            @Override
	            public void onPageFinished(WebView view, String url)
	            {
	                /* This call inject JavaScript into the page which just finished loading. */
	                browser.loadUrl("javascript:window.HTMLOUT.showHTML('<html>'+document.getElementsByTagName('html')[0].innerHTML+'</html>');");
	            }
	        });

	        /* load a web page */
	        browser.loadUrl(url);
	}
	
	
}
